package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.User;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.RedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;

/**
 * @desc：秒杀下单
 * @author: weili23
 * @params
 * @Date: 2024/3/21 9:56
 * @version: 1.0
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    //引用lua脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<Long>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    //使用lua脚本
    @Override
    public Result seckillShop(Long voucherId) {
        //获取用户信息
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        //判断lua脚本返回信息
        int r = result.intValue();
        if(r != 0){
            Result.fail(r==1 ? "库存不足" : "您已经抢过此优惠券");
        }
        log.info("执行lua脚本成功后，抢单成功~");
        long orderId = redisIdWorker.nextId("order");
        return Result.ok(orderId);
    }

    //java代码实现的
    /*@Override
    public Result seckillShop(Long voucherId) {
        //1、查询秒杀商品
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        //2、商品是否到开始秒杀时间 14      13
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("商品秒杀时间未开始");
        }
        //3、商品是否结束秒杀了12  13
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("商品秒杀时间已结束");
        }
        //4、库存是否充足
        if(seckillVoucher.getStock()<1){
            return Result.fail("库存不足");
        }
        User user = UserHolder.getUser();
        //返回订单id
        //单机模式下可以
        *//*synchronized (user.getId().toString().intern()){
            //获取代理对象（事物）
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        }*//*
        //解决分布式模式下存在的问题 用redis分布式锁
        //RedisLock redisLock = new RedisLock("order:user:"+user.getId(),stringRedisTemplate);
        //尝试获取锁
        //boolean lock = redisLock.tryLock(30L);
        //使用redisson解决
        RLock lock = redissonClient.getLock("lock:order:user:" + user.getId());
        boolean islock = lock.tryLock();
        if (!islock) {
            //获取锁失败
            return Result.fail("一人只能抢一单");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            //释放锁
            lock.unlock();
        }
    }*/


    @Override
    @Transactional
    public Result createVoucherOrder(Long id){
        //5、用户是否重复购买
        User user = UserHolder.getUser();
        boolean count = query().eq("user_id", user.getId()).eq("voucher_id", id).exists();
        if(count){
            return Result.fail("您已购买过该商品");
        }
        //6、减库存
        boolean b = seckillVoucherService.update().setSql("stock=stock-1").eq("voucher_id", id).gt("stock",0).update();
        if(!b){
            return Result.fail("扣减失败，库存不足");
        }
        //7、下单 保存订单数据
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(id);
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(user.getId());
        save(voucherOrder);
        return Result.ok(orderId);
    }
}
